package com.zqh.client;

import com.zqh.thread.ClientThread;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Scanner;

/**
 * 聊天室客户端
 */
public class NioChatClient {

    private String name;

    public NioChatClient(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    // 启动客户端
    public void startClient() throws IOException {

        // 连接服务器
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));

        // 接收服务器发送的数据
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 创建线程专门执行读操作
        ClientThread clientThread = new ClientThread(selector, 1);
        new Thread(clientThread).start();

        // 向服务器发送上线的用户信息
        socketChannel.write(Charset.forName("UTF-8").encode("user:" + getName()));

        // 向服务器发送数据
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            // 一行行读取
            String message = scanner.nextLine();
            // 如果有内容则发送到服务器
            if (message.length() > 0) {
                socketChannel.write(Charset.forName("UTF-8").encode(getName() + ": " + message));
            }
            if (message.equals("exit")) {
//                clientThread.setStatus(0);
                break;
            }
        }

    }


//    public static void main(String[] args) {
//        try {
//            new NioChatClient("test").startClient();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

}
